package Util::Taobao::QueryCategoryInfo;
use Moose;
use namespace::autoclean;
use JSON;
use WWW::Curl::Easy;
use HTTP::Response;
use Digest::MD5 qw(md5_hex);
use URI::Escape;
use Encode;

sub get_cat_info {
	my ($self, $c, $appKey, $clientSecret, $gatewayUrl, $redirectUri, $oauthUri, $apiVersion) = @_;
	my %sysParams;
	$sysParams{"app_key"} = $appKey;
	$sysParams{"v"} = $apiVersion;
	$sysParams{"format"} = "json";
	$sysParams{"sign_method"} = "md5";
	$sysParams{"partner_id"} = "top-apitools";
	$sysParams{"method"} = "taobao.itemcats.get";
	my $time = `date +"%Y-%m-%d %H:%M:%S"`;
	chomp($time);
	$sysParams{"timestamp"} = $time;
	$sysParams{"fields"} = "cid,parent_cid,name,is_parent";

	my %resData;
	my $returncode;

	my $stringToBeSigned = $clientSecret;
	foreach my $key (sort(keys(%sysParams))) {
		$stringToBeSigned .= "$key$sysParams{$key}";
	}
	$stringToBeSigned .= $clientSecret;
	my $md5 = uc(md5_hex($stringToBeSigned));
	$sysParams{"sign"} = $md5;

	my $requestUrl = $gatewayUrl . "?";
	foreach my $key (sort(keys(%sysParams))) {
		$requestUrl .= "$key=" . uri_escape($sysParams{$key}) . "&";
	}

	my $curl_new = WWW::Curl::Easy->new;
	$curl_new->setopt(CURLOPT_HEADER,1);
	$curl_new->setopt(CURLOPT_URL, $requestUrl);

	my $response_new;
	$curl_new->setopt(CURLOPT_WRITEDATA,\$response_new);
	my $retcode_new = $curl_new->perform;
	
	#TODO
	$retcode_new = 0;
	if ($retcode_new == 0) {
		$response_new = HTTP::Response->parse($response_new);

		my $xml_new = $response_new->decoded_content;
		my $json_new = from_json($xml_new);

		my $items = $json_new->{'items_list_get_response'}->{'items'}->{'item'};
		my $num = 0;
		
		for my $item (@$items) {
			$resData{$num}{'title'} =  $item->{'title'};	
			$resData{$num}{'desc'} =  $item->{'desc'};	
			$resData{$num}{'detail_url'} =  $item->{'detail_url'};	
			$c->log->info($resData{$num}{'title'});
			$c->log->info($resData{$num}{'desc'});
			$c->log->info($resData{$num}{'detail_url'});
			$num ++;
		}
		$returncode = 0;
	} else {
		$returncode  = 1;
	}

	return (\%resData, $returncode);
}
__PACKAGE__->meta->make_immutable;

1;
